<?php

/**
 * 价格设置
 */
class PriceAction extends globalAction {
    private $dao, $inn, $prices;
    public function _initialize() {
		parent::_initialize();
        parent::_loginRequire();
        
        //客栈管理权限验证
        $innId = intval($_GET['innId']);
        if(empty($innId)) parent::_message('error', '未指定客栈！');
        $innDao = D('Inn');
        $this->inn = $innDao
            ->field($innDao->_map_flip)
            ->where(array(
                $innDao->_map['id'] => $innId,
                $innDao->_map['menuId'] => 585,
                $innDao->_map['uid'] => __USERID__
            ))
            ->find();
        if(empty($this->inn)) parent::_message('error','您无权管理此客栈');
        $this->assign('inn', $this->inn);
        
        //获取价格时间段
        $this->dao = D('InnBatPrice');
        if(!empty($_POST['add'])) return;//当添加时间段的时候无需获取时间段列表
        $this->prices = $this->dao
            ->field($this->dao->_map_flip)
            ->where(array(
                $this->dao->_map['innId'] => $innId,
                $this->dao->_map['menuId'] => 612
            ))
            ->select();
        $this->assign('prices', $this->prices);
	}
    
    public function index() {
        //获取当前查看的时间段设置
        $priceID = intval($_GET['pid']);
        if(!empty($priceID)) {
            foreach($this->prices as $price) {
                if($price['id'] == $priceID) {
                    $priceList = $this->unPackPrices($price['price_data']);
                    //查找房型列表
                    $roomDao = D('InnRoom');
                    $roomList = $roomDao
                        ->field($roomDao->_map_flip)
                        ->where(array(
                            $roomDao->_map['menuId'] => 601,
                            $roomDao->_map['innId'] => $this->inn['id']
                        ))
                        ->order(array(
                            $roomDao->_map['display_order'] => 'asc'
                        ))
                        ->select();

                    $roomCount = count($roomList);
                    for($i=0; $i < $roomCount; $i++) {
                        $roomId = $roomList[$i]['id'];
                        $roomList[$i]['priceSet'] = $priceList[$roomId];
                    }
                    $this->assign('roomList', $roomList);
                    $this->assign('price', $price);
                    break;
                }
            }
        }
        $this->display();
    }
    
    public function dayprice() {
        $roomid = intval($_GET['roomid']);
        if(empty($roomid)) parent::_message('error', '未指定房型！');
        //查找房型
        $roomDao = D('InnRoom');
        $room = $roomDao
            ->field($roomDao->_map_flip)
            ->where(array(
                $roomDao->_map['id'] => $roomid,
                $roomDao->_map['menuId'] => 601,
                $roomDao->_map['innId'] => $this->inn['id']
            ))
            ->find();
        if(empty($room)) parent::_message('error', '未找到房型！');

        $this->assign('room', $room);
        $this->display();
    }
    
    public function op() {
        if(!empty($_POST['add'])) {
            $_POST['innId'] = $this->inn['id'];
            if($this->dao->create()) {
                $result = $this->dao->add();
                if(false !== $result) {
                    redirect( C('TMPL_PARSE_STRING.__KZURL__') . '/price/index-innId-' . $this->inn['id'] . '-pid-' . $result);
                } else {
                    parent::_message('error', '添加失败！请联系管理员！', $_SERVER['HTTP_REFERER']);
                }
            } else {
                parent::_message('error', implode('<br />', $this->dao->getError()), $_SERVER['HTTP_REFERER']);
            }
        } elseif(!empty($_POST['modify'])) {
            $_POST['innId'] = $this->inn['id'];
            $_POST['price_data'] = $this->packPrices($_POST['prices']);
            if($this->dao->create()) {
                //防止偷取别人的价格信息
                $result = $this->dao->where(array(
                    $this->dao->_map['id'] => intval($_POST['id']),
                    $this->dao->_map['innId'] => intval($_POST['innId'])
                ))->save();
                if(false !== $result) {
                    //远程触发[自动计算房型最低价]
                    global $SYS_config, $SystemConest;
                    $uri = $SYS_config['siteurl'].'/'.$SystemConest[1].'/u.php/hotelroom/updateroomminprice/hid/'.$this->inn['id'];
                    @file_get_contents($uri);
                    redirect( C('TMPL_PARSE_STRING.__KZURL__') . '/price/index-innId-' . $this->inn['id'] . '-pid-' . $_POST['id']);
                } else {
                    parent::_message('error', '保存失败！请联系管理员！', $_SERVER['HTTP_REFERER']);
                }
            } else {
                parent::_message('error', implode('<br />', $this->dao->getError()), $_SERVER['HTTP_REFERER']);
            }
        } elseif(!empty($_GET['delete'])) {
            $priceID = intval($_GET['delete']);
            $this->dao->where(array(
                    $this->dao->_map['id'] => $priceID,
                    $this->dao->_map['innId'] => $this->inn['id']
                ))->delete();
            redirect( C('TMPL_PARSE_STRING.__KZURL__') . '/price/index-innId-' . $this->inn['id']);
        }
    }
    
    public function do_delete() {
        $this->dao->delete($this->dateSetData['id']);
        redirect( C('TMPL_PARSE_STRING.__KZURL__') . '/DateSet/index-innid-' . $this->inn['id']);
    }
    
    /**
     * 打包价格数据
     * @param $prices array(
     *   '房型ID'=>array(
     *       '价格属性代码'=>'价格'
     *       ...
     *   )...)
     */
    private function packPrices($prices) {
        $price_data = array();
        foreach($prices as $roomId => $price) {
            if(empty($price)) continue;
            $roomPrice  = '{id:'.$roomId.'}';
            foreach($price as $key => $val) {
                $roomPrice  .= '{'.$key.':'.$val.'}';
            }
            $price_data[] = $roomPrice;
        }
        return implode(',', $price_data);
    }
    
    /**
     * 解包价格数据
     * @param $price_data String
     */
    private function unPackPrices($price_data) {
        $priceList = array();
        if(!empty($price_data)) {
            $prices = explode(',', $price_data);
            foreach($prices as $price) {
                preg_match_all('/\{(\w+\:\w+)\}/', $price, $matches);
                $attr = array();
                foreach($matches[1] as $val) {
                    $keyval = explode(':', $val);
                    $attr[$keyval[0]] = $keyval[1];
                }
                $priceList[$attr['id']] = $attr;
            }
        }
        return $priceList;
    }
}